package framework;

import java.awt.Graphics2D;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;


/**
 * Framework class for the Game driver
 * 
 * @author Michael Deng
 * 
 */
public class Game {

    private static int ourLevelCounter = 1;
    private Level myCurrentLevel;
    private GameContainer myContainer;
    private Factory<Level> myLevelFactory;
    private String myGamePackage;

    /**
     * 
     * @param c the GameContainer class
     */
    protected Game (GameContainer c, String gamePackage) {
        myContainer = c;
        myGamePackage = gamePackage;
        myLevelFactory = new Factory<Level>(myGamePackage + ".level");
        initializeNextLevel(ourLevelCounter);
    }

    /**
     * Updates the game
     */
    protected void update () {
        myCurrentLevel.update();

    }

    /**
     * Gets name of the game package.
     * 
     * @return
     */
    public String getGamePackage () {
        return myGamePackage;
    }

    /**
     * Paints all objects in the game
     * 
     * @param pen used to paint objects (associated with applet)
     */
    protected void paint (Graphics2D pen) {
        myCurrentLevel.paint(pen);
    }

    /**
     * Called to initialize the next level
     * 
     * @param nextLevel int representing the next level class
     */
    public void initializeNextLevel (int nextLevel) {
        ourLevelCounter = nextLevel;
        loadNextLevel();
        myCurrentLevel.initialize(this);
    }

    /**
     * Method uses recursive call the find and load the next level
     */
    private void loadNextLevel () {
        myCurrentLevel = myLevelFactory.createObject("Level" + Integer.toString(ourLevelCounter));
        if (myCurrentLevel == null) {
            ourLevelCounter = 1;
            loadNextLevel();
        }
    }

    /**
     * Returns a specific image. The given directory should be given relative to
     * the source code, this function will find its absolute location.
     * 
     * @param file filename of image
     */
    public Image loadImage (String file) {
        try {
            File path = new File("src/" + myGamePackage + "/images/" + file);
            return ImageIO.read(path);

        }
        catch (IllegalArgumentException e) {
            // happens when trying to load a null image file (imageless sprites)
            System.out.println("Illegal Argument");
        }
        catch (IOException e) {
            // also happens when trying to load a null image file
            System.out.println("IOException");
        }
        return null;
    }

    /**
     * Getter for gamecontainer
     * 
     * @return reference to gamecontainer object
     */
    public GameContainer getMyContainer () {
        return myContainer;
    }

}
